package com.weic.spark.scala.p3

import org.apache.spark.sql.SparkSession

/**
 * @Auther:BigData-weic
 * @ClassName:_01SparkSqlUDFOps
 * @Date:2020/12/10 23:06
 * @功能描述: 自定义函数UDF
 * @Version:1.0
 */
object _01SparkSqlUDFOps {

	def main(args: Array[String]): Unit = {
		val spark = SparkSession.builder()
    		.master("local[*]")
    		.appName("_01SparkSqlUDFOps")
    		.getOrCreate()
		//注册
		spark.udf.register[Int,String]("myLen",str => asdf(str))
		//加载数据
		val df = spark.read.json("file:\\F:\\datas\\spark\\sql\\people.json")
		//注册临时表
		df.createOrReplaceTempView("person")
		//查询单词长度
		val sql =
			"""
			  |select
			  |  name,
			  |  length(name),
			  |  myLen(name) myLen
			  |from person
			  |""".stripMargin
		spark.sql(sql).show()
		//释放资源
		spark.stop()

	}
	//自定义UDF函数  定义一个方法，然后进行注册
	def asdf(name:String): Int={
		name.length
	}
}

